<?php
namespace GuessSong\Controller;
use Common\Controller\GuessSongController;

class IndexController extends GuessSongController {

    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     * 获取排行
     */
    public function getranking(){

        $state = I('post.state','','int');

        if (!$state){
            $this->returnData('','参数错误',401);
        }
        $ranking = "";
        //荣誉排行
        if ($state=='1'){
            $whre['score'] = array('gt',0);
            $ranking = M('SongMember')->field('nickName,avatarUrl,score')->where($whre)->limit(100)->order('score desc')->select();
            //$ranking = $this->moni();

        }
        //毅力排行
        if ($state=='2'){
            $ranking = $this->getcacherank();
        }
        if ($ranking){
            $this->returnData($ranking,'成功',200);
        }else{
            $this->returnData('','失败',100);
        }

    }

    /**
     * 获取个人信息
     */

    public function getmemberinfo(){

        $member_id = I('post.member_id','','int');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $member = M('SongMember')->field('nickName,avatarUrl,opportunity,number,score,prize,giveopportunity')->where(array('song_member_id'=>$member_id))->find();

        $member['opportunity'] = $member['opportunity']+$member['giveopportunity'];
        if ($member){
            $this->returnData($member,'成功',200);
        }else{
            $this->returnData('','失败',100);
        }

    }

    /**
     * 版本（3）个人信息
     */
    public function getinfo(){

        $member_id = I('post.member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');
        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $member = M('SongMember')->field('opportunity,number,score,giveopportunity')->where(array('song_member_id'=>$member_id))->find();

        $sum = M('song_getgift')->where(array('song_member_id'=>$member_id))->count();

        $member['giftnum'] = $sum;
        $member['opportunity'] = $member['opportunity']+$member['giveopportunity'];
        $member['url'] = '/pages/index/index';
        $member['appid'] = 'wx6b1c7907c5733fc9';

        $data['member'] = $member;
//
        $data['rule'] =array(
            '1.每人每天可以获得三次挑战机会,分享到不同的群可以获得更多的挑战机会',
            '2.挑战一共有40道题，全部答对可以获得娃娃一个',
            '3.娃娃领取后将在10个工作日内发出',
            '4.有任何问题请联系客服处理'
        );

        $this->returnData($data);

    }

    /**
     * 广告
     */
    public function getdata_ad(){

        $appid = I('post.appid','','htmlspecialchars');

        $data = M('song_ad')->field('content,title',true)->where(array('isshow'=>'1'))->select();

        foreach ($data as $key=>$val){
            $data[$key]['logo'] = $this->url.$data[$key]['logo'];
        }

        $this->returnData($data);

    }

    /**
     * 获取挑战机会
     */
    public function getopportunity(){

        $member_id = I('post.member_id','','int');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $date = date('Y-m-d',time());

        $where['song_member_id'] = $member_id;
        $where['signin_time'] = $date;

        $issign="";
        $issign = M('SongSignin')->where($where)->getField('signin_num'); //判断今天有没有签到
        if (!$issign||$issign==""){
                $data = array(
                    'song_member_id'=>$member_id,
                    'signin_time'=>$date,
                    'signin_num'=>'1'
                );
            M('SongSignin')->data($data)->add();
            M('SongMember')->where(array('song_member_id'=>$member_id))->save(array('giveopportunity'=>'2')); //每天2次机会
        }

        $opportunity = M('SongMember')->field('opportunity,giveopportunity')->where(array('song_member_id'=>$member_id))->find();//获取挑战机会
        $chang = $opportunity['opportunity']+$opportunity['giveopportunity'];

        if ($chang>0){

            if ($opportunity['giveopportunity']>0){
                M('SongMember')->where(array('song_member_id'=>$member_id))->setDec('giveopportunity'); //先减赠送的
            }else{
                M('SongMember')->where(array('song_member_id'=>$member_id))->setDec('opportunity'); //挑战机会减一
            }

            M('SongMember')->where(array('song_member_id'=>$member_id))->setInc('number'); //挑战次数加一

            $data['opportunity'] = $chang;
            $this->returnData($data,'成功',200);
        }

        $this->returnData(array('opportunity'=>$chang),'没有挑战机会',101);


    }

//    /**
//     * 挑战版本1 已弃用
//     */
//
//    public function challenge(){
//
//        $member_id = I('post.member_id','','int');
//
//        $state = I('post.state','','int');
//
//        $carnet = I('post.carnet','','int');
//
//        $opportunity = I('post.opportunity','','int');
//
//
//        if ($member_id==""||$opportunity==""||$opportunity<1||$carnet==""){
//            $this->returnData('','没有挑战机会',101);
//        }
//
//        //获取随机值
//        $songquersion = $this->getmanyquersion(40);
//
//
//        if ($songquersion){
//            $this->returnData($songquersion,'成功',200);
//        }else{
//            $this->returnData('','获取歌曲题目失败',100);
//        }
//
//
//    }

    /**
     * 获取题库（版本2）
     */

    public function getquestions(){


        $songquersion = $this->getmanyquersion(40);

        if ($songquersion){
            $data['count'] = 40; //关数
            $data['ishow'] = true; //是否显示分享复活
            $data['ishow2'] = true; //是否显示分享复活
            $this->returnData($songquersion,$data,200);
        }else{
            $this->returnData('','获取歌曲题目失败',100);
        }

    }

    /**
     * 通关40关
     */
    public function pass(){
        $member_id = I('post.member_id','','int');
        $carnet = I('post.carnet','','int');
        if (!$member_id||!$carnet){
            $this->returnData('','参数错误',401);
        }
        //通过40关
        if ($carnet=='40'){
            $songquersion['pass'] = 'successful';
            M('SongMember')->where(array('song_member_id'=>$member_id))->setInc('prize'); //领奖机会加一
            M('SongMember')->where(array('song_member_id'=>$member_id))->setInc('score'); //分数加一
            $this->returnData($songquersion,'获得一次领取礼物的机会',1);

        }
    }


    /**
     * 微信群分享记录
     */
    public function sharerecord(){

        $song_member_id = I('post.member_id','','int');
        $shareType = I('post.shareType','2','int');
         $encryptedData = $_POST['encryptedData'];
         $iv = $_POST['iv'];

         if ($shareType=="3"){
            // M('SongMember')->where(array('song_member_id'=>$song_member_id))->setInc('opportunity'); //挑战机会加一

             $opportunity = M('SongMember')->field('opportunity,giveopportunity')->where(array('song_member_id'=>$song_member_id))->find();//获取挑战机会
             $chang = $opportunity['opportunity']+$opportunity['giveopportunity'];

             $this->returnData(array('repetition'=>'no','opportunity'=>$chang),'分享成功',200);
         }


        if (!$encryptedData||!$song_member_id||!$iv){
            $this->returnData('','参数错误',401);
        }


        $info = M('SongMember')->field('appid,session_key')->where(array('song_member_id'=>$song_member_id))->find();

        $appid = $info['appid'];
        $sessionkey = $info['session_key'];

        $openGId = $this->getopenGId($appid,$sessionkey,$encryptedData,$iv);

        if ($openGId=='-1'){
            $this->returnData('','分享失败',100);
        }

        $time = date('Y-m-d',time());

        $where['sharetime'] = $time;
        $where['song_member_id'] = $song_member_id;
        $where['openGId'] = $openGId;
        if ($shareType=='1'){
            $interior = $record = M('song_interior_group')->where($where)->getField('sharenum'); //判断是否已分享
            if ($interior){
                M('song_interior_group')->where($where)->setInc('sharenum');
                $this->returnData(array('repetition'=>'yes'),'今天已分享',201);
            }
            //如果没分享过则插入，用户挑战机会加一
            $data = array(
                'openGId'=>$openGId,
                'sharetime'=>$time,
                'sharenum'=>1,
                'song_member_id'=>$song_member_id,
            );

            M('song_interior_group')->data($data)->add();
            $this->returnData(array('repetition'=>'repetition'),'立即复活',200);
        }


        $record = "";
        $record = M('SongWechatGroup')->where($where)->getField('sharenum'); //判断是否已分享

        //如果已分享则自增分享次数然后返回
        if ($record){
            M('SongWechatGroup')->where($where)->setInc('sharenum');

            $this->returnData(array('repetition'=>'yes'),'今天已分享',201);
        }

        //如果没分享过则插入，用户挑战机会加一
        $data = array(
            'openGId'=>$openGId,
            'sharetime'=>$time,
            'sharenum'=>1,
            'song_member_id'=>$song_member_id,
        );

        M('SongWechatGroup')->data($data)->add();

        M('SongMember')->where(array('song_member_id'=>$song_member_id))->setInc('opportunity'); //挑战机会加一

        $opportunity = M('SongMember')->field('opportunity,giveopportunity')->where(array('song_member_id'=>$song_member_id))->find();//获取挑战机会
        $chang = $opportunity['opportunity']+$opportunity['giveopportunity'];

        $this->returnData(array('repetition'=>'no','opportunity'=>$chang),'分享成功',200);
    }

    /**
     * 获取礼品列表
     */
    public function giftlist(){

        $member_id = I('post.member_id','','int');

        $getgift = "";
        $getgift = M('song_getgift')->field('song_gift_id,getcode')->where(array('song_member_id'=>$member_id))->select();

        $gift = $this->getcachegift();

        if ($getgift!=""&&$getgift){

            foreach ($gift as $key=>$value){
                $gift[$key]['get'] = 'no';
                for ($i=0;$i<count($getgift);$i++){
                    if ($value['song_gift_id']==$getgift[$i]['song_gift_id']){
                        $gift[$key]['get'] = 'yes';
                        $gift[$key]['getcode'] =$getgift[$i]['getcode'];
                    }
                }
            }

        }

        $this->returnData($gift);

    }

    /**
     * 用户领取礼品
     */
    public function getgift(){

        $gift_id = I('post.gift_id','','int');
        $member_id = I('post.member_id','','int');

        if (!$gift_id||!$member_id){
            $this->returnData('','参数错误',401);
        }
        $prize = "";
        $prize = M('SongMember')->where(array('song_member_id'=>$member_id))->getField('prize');
        if ($prize<1||$prize==""){
            $this->returnData('','挑战成功即可领取',0);
        }
        $getgiftid = "";
        $getgiftid = M('song_getgift')->where(array('song_member_id'=>$member_id,'song_gift_id'=>$gift_id))->getField('song_getgift_id');

        if ($getgiftid!=""||$getgiftid){
            $this->returnData('','该礼品已领取',100);
        }
        $getid = M('song_getgift')->max('song_getgift_id')+1;
        $getcode = $getid.$member_id.$gift_id.date('YmdHis');
        $data = array(
            'song_gift_id'=>$gift_id,
            'song_member_id'=>$member_id,
            'createtime'=>date('Y-m-d H:i:s'),
            'getcode'=>$getcode,
        );
        $add = M('song_getgift')->data($data)->add();

        if ($add){
            M('SongMember')->where(array('song_member_id'=>$member_id))->setDec('prize'); //领奖机会减一
            $this->returnData(array('getcode'=>$getcode),'领取成功,你的领取码为：'.$getcode,200);
        }else{
            $this->returnData('','抱歉，领取失败',100);
        }

    }

    /**
     * 分享模板
     */
    public function sharetmp(){

        $appid = I('post.appid','','htmlspecialchars');

        $data = array(
            'title'=>'@我，快来猜歌，闯关成功还送娃娃！',
            'imgsrc'=>$this->url.'appshow/caigebanner.jpg',
        );
        $this->returnData($data);

    }

    /**
     * 用户的领奖记录
     */
    public function mygetgiftrecord(){

        $member_id = I('post.member_id','','int');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $gift = "";
        $gift = M('song_getgift')->field('song_gift_id,getcode,createtime,issend')->where(array('song_member_id'=>$member_id))->select();

        //有待优化
        foreach ($gift as $key=>$value){

            $record = M('song_gift')->field('giftname,giftsrc')->where(array('song_gift_id'=>$value['song_gift_id']))->find();
            $gift[$key]['giftname'] = $record['giftname'];
            $gift[$key]['giftsrc'] = $this->url.$record['giftsrc'];
        }

        $this->returnData($gift);

    }

    /**
     * 更多好玩
     */
    public function getappshow(){

        $app = M('song_appshow')->field('isshow',true)->where(array('isshow'=>'1'))->select();

        foreach ($app as $key=>$value){
            $app[$key]['logo'] = $this->url.$app[$key]['logo'] ;
        }
        $this->returnData($app);

    }


        /**
     * 存放模板消息
     */
    public function send()
    {
        $appid = I('post.appid','','htmlspecialchars');
        $touser = I('post.touser','','htmlspecialchars');
        $page = I('post.page','','htmlspecialchars');
        $form_id = I('post.form_id','','htmlspecialchars');
        $form_type = I('post.form_type','','htmlspecialchars');
        $secret = I('post.secret','','htmlspecialchars');

        $template_id = I('post.template_id','','htmlspecialchars');

       if ($appid==""||$touser==""||$page==""||$form_id==""||$form_type==""||$secret==""||$template_id==""){
           $this->returnData('','参数错误','401');
       }

        $date = date('Y-m-d');
        $insert = array(
            'appid'=>$appid,
            'touser'=>$touser,
            'template_id'=>$template_id,
            'page'=>$page,
            'form_id'=>$form_id,
            'form_type'=>$form_type?$form_type:1,
            'status'=>'-1',
            'add_time'=>time(),
            'secret'=>$secret,
            'createtime'=>$date,
        );

        M('song_template_send')->data($insert)->add();
        $this->returnData('成功','200');

        $where['touser'] = $touser;
        $where['template_id'] = $template_id;
        $where['createtime'] = $date;
        $where['status'] = '-1';

        $ishave = M('song_template_send')->field('wxopen_template_send_id')->where($where)->find();

        if ($ishave){
            M('song_template_send')->where(array('wxopen_template_send_id'=>$ishave['wxopen_template_send_id']))->save($insert);
        }else{
            M('song_template_send')->data($insert)->add();
        }

        $this->returnData('成功','200');

    }



}